package com.qianyucc.blog.global;

import cn.hutool.core.io.*;
import cn.hutool.core.util.*;
import com.alibaba.fastjson.*;
import com.qianyucc.blog.model.entity.*;
import com.qianyucc.blog.model.pojo.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.mapper.*;
import com.qianyucc.blog.service.*;
import com.qianyucc.blog.utils.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.data.redis.core.*;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.*;

import java.util.*;

/**
 * @author lijing
 * @date 2019-10-14 11:48
 * @description 定时任务
 */
@Component
public class BlogSchedule {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private BlogService blogService;
    @Value("${blog.backup}")
    private String path;

    /**
     * 每三小时更新一次
     */
    @Scheduled(cron = "0 0 */3 * * ?")
    public void updateHotArticles() {
        List<ArticleDO> articleDOS = articleMapper.findAll();
        List<SimpleArticleVO> hotArticles = Utils.getHotArticles(articleDOS);
        redisTemplate.opsForValue().set("hotArticles", JSON.toJSONString(hotArticles));
    }

    /**
     * 每天凌晨一点钟备份一次数据
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void backup() {
        BlogData blogData = blogService.export();
        FileUtil.writeBytes(ObjectUtil.serialize(blogData), path);
    }
}